<?php

/* BEGIN License Block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 *
 * Version: EPL 1.0
 *
 * The contents of this file are subject to the Eclipse Public License Version
 * 1.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *
 * http://www.opensource.org/licenses/eclipse-1.0.txt
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * Copyright (C) 2009 Benry Yip <benryyip@mail.utexas.edu>
 * 
 * END License Block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

class LeafTwitter {

    protected $debug; // Boolean: turns debug output on and off.

    /* LeafTwitter constructor.
     *
     * Defaults ---
     *
     *     Debug Mode: Off
     */
    function __construct($debug = false) {

        $this->debug = $debug;

        $this->dprint("New LeafTwitter object created.");
    }

    /* Get the current status of $username.
     */
    function getStatus($username) {

        // Turn off warnings when not in debug mode.
        if($this->debug) {
            error_reporting(E_ALL ^ E_NOTICE);
        } else {
            error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
        }

        $feed = "http://twitter.com/statuses/user_timeline/$username.xml";

        $status = "Whoops! There's no Twitter here!";        

        $reader = new XMLReader();
        
        if($reader->open($feed)) {
            
            // Find the first Status element and output the text.
            $done = false;
            
            while($reader->read() && !$done) {
                
                if($reader->nodeType == XMLReader::ELEMENT &&
                   $reader->localName == "text") {
                    
                    $reader->read();
                    $status = $reader->value;
                    
                    $done = true;
                }
            }
        }

        $this->printStatus($status);
    }

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PRIVATE

    /* Prints out a formatted status.
     */
    private function printStatus($status) {

        $openTag  = "<div class=\"leaf-twitter\">";
        $closeTag = "</div>\n\n";

        echo $openTag . $status . $closeTag;
    }
        
    /* Prints out debug messages if debug mode is enabled.
     */
    private function dprint($message) {

        $openDebug  = "<h3 class=\"leaf-twitter-debug\">";
        $closeDebug = "</h3>\n\n";

        if($this->debug) {
            echo $openDebug . $message . $closeDebug;
        }
    }
}

?>